package wxpay

import (
	"crypto/rsa"
	"crypto/x509"
	"encoding/json"
	"errors"
	"fmt"
	"time"
)

type MchJsApi struct {
	WxPayMch
}

func NewMchJsApi(mchid, appid, mch_api_key string, pem_cert *x509.Certificate, pem_key *rsa.PrivateKey) *MchJsApi {
	ent := &MchJsApi{}
	ent.Appid = appid
	ent.Mchid = mchid
	ent.MchAPIKey = mch_api_key
	ent.MchPrivateKey = pem_key
	ent.MchCertificate = pem_cert
	return ent
}

//支付统一下单
func (ent *MchJsApi)CreateOrder(data JsApiOrderData) (WxAppPayParam, error)  {
	var preq JsApiOrderCreateReq
	preq.Appid = ent.Appid
	preq.Mchid = ent.Mchid
	preq.JsApiOrderData = data
	preq.JsApiOrderData.Sub_mchid = ""
	preq.JsApiOrderData.Sub_appid = ""
	data_body, _ := json.Marshal(preq)

	var param_ent WxAppPayParam
	var pret JsApiOrderCreateRet
	const url = "https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi"
	result, err := WxPayPostV3(&ent.MchParam, url, data_body)
	if err != nil {
		return param_ent, err
	}

	err = json.Unmarshal([]byte(result), &pret)
	if err != nil {
		return param_ent, err
	}

	if pret.Prepay_id == "" {
		return param_ent, errors.New(pret.Return_msg)
	}

	//小程序客户端支付参数
	param_ent.Appid = preq.Appid
	param_ent.TimeStamp = fmt.Sprintf("%d", time.Now().Unix())
	param_ent.NonceStr, _= GenerateNonce()
	param_ent.Prepay_id = pret.Prepay_id
	param_ent.Package = "prepay_id=" + pret.Prepay_id
	param_ent.SignType = "RSA"
	param_ent.PaySign, _ = param_ent.GenPaySignV3(ent.MchPrivateKey)
	return param_ent, nil
}

